package com.central.scheduler.dao;

import com.central.db.mapper.SuperMapper;
import com.central.scheduler.dao.mapper.PluginDefineMapper;
import com.central.scheduler.dao.model.PluginDefine;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

import static java.util.Objects.requireNonNull;

/**
 * @author Tindy
 * @date 2021/10/29
 * @describe
 */
@Component
public class PluginDao extends AbstractBaseDao {
    @Autowired
    private PluginDefineMapper pluginDefineMapper;

    /**
     * add or update plugin define
     *
     * @param pluginDefine new pluginDefine
     */
    public Long addOrUpdatePluginDefine(PluginDefine pluginDefine) {
        requireNonNull(pluginDefine, "pluginDefine is null");
        requireNonNull(pluginDefine.getPluginName(), "pluginName is null");
        requireNonNull(pluginDefine.getPluginType(), "pluginType is null");

        List<PluginDefine> pluginDefineList = pluginDefineMapper.queryByNameAndType(pluginDefine.getPluginName(), pluginDefine.getPluginType());
        if (CollectionUtils.isEmpty(pluginDefineList)) {
            pluginDefineMapper.insert(pluginDefine);
            return pluginDefine.getId();
        }
        PluginDefine currPluginDefine = pluginDefineList.get(0);
        if (!currPluginDefine.getPluginParams().equals(pluginDefine.getPluginParams())) {
            currPluginDefine.setPluginParams(pluginDefine.getPluginParams());
            pluginDefineMapper.updateById(currPluginDefine);
        }
        return currPluginDefine.getId();
    }

}